<%@ page import="org.ow2.bonita.util.BonitaConstants" %>
<%@ page import="org.ow2.bonita.util.Misc"%>
<%@ page import="org.ow2.bonita.util.SimpleCallbackHandler"%>
<%@ page import="javax.security.auth.login.LoginContext"%>
<%@ page import="java.net.URL"%>
<%@ page import="org.ow2.bonita.facade.ManagementAPI"%>
<%@ page import="org.ow2.bonita.util.AccessorUtil"%>

<%
try {
  final String username = request.getParameter("username");
  final String password = request.getParameter("password");

  if (System.getProperty(BonitaConstants.JAAS_PROPERTY) == null) {
    final URL jaasFile = this.getClass().getClassLoader().getResource("jaas-standard.cfg"); 
    if (jaasFile != null) {
      System.setProperty(BonitaConstants.JAAS_PROPERTY, jaasFile.toURI().getPath());
    }
  }
  final LoginContext authLC = new LoginContext("BonitaAuth", new SimpleCallbackHandler(username, password));
  authLC.login();
  authLC.logout();
  
  final LoginContext storeLC = new LoginContext("BonitaStore", new SimpleCallbackHandler(username, password));
  storeLC.login();
  final ManagementAPI managementAPI = AccessorUtil.getManagementAPI();
  final Boolean isAdmin =new Boolean(managementAPI.isUserAdmin(username));
  storeLC.logout();
  
  request.getSession().setAttribute("username", username);
  request.getSession().setAttribute("isadmin", isAdmin);
  
  System.out.println(username);
  response.sendRedirect("../home.jsp");
} catch (Exception e) {
  e.printStackTrace();
  Throwable t = e;
  while (t.getCause() != null) {
    t = t.getCause();
  }
  final String msg = "Unable to login: " + t.getMessage();
  response.sendRedirect("../index.jsp?msg=" + msg);
}
%>
